package com.hgxd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.PeekingIterator;
import com.hgxd.entity.pojo.SysRole;
import com.hgxd.entity.pojo.SysUserRole;
import com.hgxd.entity.vo.ReqUserRoleVo;
import com.hgxd.exception.ServiceException;
import com.hgxd.mapper.SysRoleMapper;
import com.hgxd.mapper.SysUserRoleMapper;
import com.hgxd.result.ResultCodeEnum;
import com.hgxd.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author wtf
 */
@Service("sysUserRoleServiceImpl")
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateRoleByUserId(ReqUserRoleVo reqUserRoleVo) {

        // 1 删除已有的roleIds
        sysUserRoleMapper.delete(new QueryWrapper<SysUserRole>().eq("user_id", reqUserRoleVo.getUserId()));
        // 2 添加现有的roleIds
        List<Long> roleIds = reqUserRoleVo.getRoleId();
        for (Long roleId : roleIds) {
            Boolean b = sysUserRoleMapper.insertByUserId(reqUserRoleVo.getUserId(), roleId);
            if (!b) {
                throw new ServiceException(ResultCodeEnum.SERVICE_ERROR, "添加失败");
            }
        }
        return true;
    }
}
